package per.turtle.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import per.turtle.common.core.constant.CacheConstants;
import per.turtle.common.core.exception.CustomException;
import per.turtle.common.redis.service.RedisService;
import per.turtle.system.entity.SysConfig;
import per.turtle.system.mapper.SysConfigMapper;
import per.turtle.system.service.ISysConfigService;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;

/**
 * 参数配置 服务层实现
 *
 * @author turtle
 */
@RequiredArgsConstructor
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

    private final SysConfigMapper configMapper;

    private final RedisService redisService;

    @Override
    public boolean checkConfigKeyUnique(SysConfig config) {
        QueryWrapper<SysConfig> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(StrUtil.isNotBlank(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey())
               .ne(config.getConfigId() != null, SysConfig::getConfigId, config.getConfigId());
        List<SysConfig> infos = baseMapper.selectList(wrapper);
        return infos.isEmpty();
    }

    @CacheEvict(value = CacheConstants.SYS_CONFIG_KEY, key = "#config.configKey")
    @Override
    public void deleteConfig(SysConfig config) {
        if (config.getIsPreset()) {
            throw new CustomException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
        }
        configMapper.deleteById(config);
    }

    @CacheEvict(value = CacheConstants.SYS_CONFIG_KEY, key = "#config.configKey")
    @Override
    public int insertConfig(SysConfig config) {
        return configMapper.insert(config);
    }

    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    @Override
    public SysConfig selectConfigById(Long configId) {
        return configMapper.selectById(configId);
    }

    @Override
    public List<SysConfig> selectConfigList(SysConfig config) {
        QueryWrapper<SysConfig> wrapper = new QueryWrapper<>(config);
        wrapper.getEntity().setConfigKey(null);
        wrapper.getEntity().setConfigName(null);
        wrapper.lambda().like(StrUtil.isNotBlank(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey())
               .like(StrUtil.isNotBlank(config.getConfigName()), SysConfig::getConfigName, config.getConfigName());
        return configMapper.selectList(wrapper);
    }

    @Cacheable(value = CacheConstants.SYS_CONFIG_KEY, key = "#configKey")
    @Override
    public String selectConfigValueByKey(String configKey) {
        QueryWrapper<SysConfig> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysConfig::getConfigKey, configKey);
        SysConfig config = configMapper.selectOne(wrapper);
        return config == null ? null : config.getConfigValue();
    }

    @CacheEvict(value = CacheConstants.SYS_CONFIG_KEY, key = "#config.configKey")
    @Override
    public int updateConfig(SysConfig config) {
        return configMapper.updateById(config);
    }

    /**
     * 初始化配置参数到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    /**
     * 清空参数缓存数据
     */
    private void clearConfigCache() {
        Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        redisService.deleteObject(keys);
    }

    /**
     * 加载参数缓存数据
     */
    private void loadingConfigCache() {
        QueryWrapper<SysConfig> wrapper = new QueryWrapper<>();
        List<SysConfig> configsList = configMapper.selectList(wrapper);
        for (SysConfig config : configsList) {
            redisService.setCacheObject(CacheConstants.getCacheKey(CacheConstants.SYS_CONFIG_KEY, config.getConfigKey()), config.getConfigValue());
        }
    }

}
